package com.lj.api.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class JsonUtils {
    public static String toJsonString(Object o){
        Gson gson = new GsonBuilder()
                .registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory())
        .serializeNulls()
        .setLongSerializationPolicy(LongSerializationPolicy.STRING)
        .setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        return gson.toJson(o);
    }
    public static <T> T parseObject(String jsonString,Class<T> aClass){
        return JSON.parseObject(jsonString,aClass);
    }

    public static JSONObject parseObject(String jsonString){
        return JSON.parseObject(jsonString);
    }

    public static void main(String[] args) {
        System.out.println("@@@@@@@@@@@@@@@@");
        Map map = new HashMap();
        map.put("id",Long.valueOf(1231231));
        map.put("asest",null);
        String s = JsonUtils.toJsonString(map);
        System.out.println(s);

    }
}


class StringAdapter extends TypeAdapter<String> {
    @Override
    public void write(JsonWriter out, String value) throws IOException {
        if (value == null) {
            out.value("");
            return;
        }
        out.value(value);
    }

    @Override
    public String read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return "";
        }
        return in.nextString();
    }
}

class NullStringToEmptyAdapterFactory implements TypeAdapterFactory {
    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        Class<T> rawType = (Class<T>) type.getRawType();
        if (rawType != String.class) {
            return null;
        }
        return (TypeAdapter<T>) new StringAdapter();
    }
}
